/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.android.receiver;

import java.util.Map;

import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.View;

import com.hercules.android.receiver.entities.XREObject;
import com.hercules.android.receiver.entities.XREView;
import com.hercules.android.receiver.painter.XREPainter;
import com.hercules.android.receiver.painter.XREPainterException;

/**
 * This class is the root view of the application. It will paint the XRE root
 * view to canvas.
 * 
 * @author TCSASSEMBER
 * @version 1.0
 */
public class MainView extends View {
    /**
     * Represents the <code>Receiver</code> instance.
     */
    private Receiver receiver;

    /**
     * Create a new <code>MainView</code> with the <code>Context</code> and
     * <code>Receiver</code> instances.
     * 
     * @param context
     *            the <code>Context</code> instance.
     * @param receiver
     *            the <code>Receiver</code> instance.
     * @throws IllegalArgumentException
     *             if arguments is null
     */
    public MainView(Context context, Receiver receiver) {
        super(context);
        ReceiverUtil.checkNull("receiver", receiver);
        this.receiver = receiver;
    }

    /**
     * Override the onDraw method to paint XRE root view to canvas.
     * 
     * @param canvas
     *            the <code>Canvas</code> that paint views on
     */
    protected void onDraw(Canvas canvas) {
        synchronized (receiver.getApplicationData().getDataLockObject()) {
            XREPainter painter = receiver.getApplicationData().getObjectPainters().get(Config.XRE_KLASS_VIEW);
            Map<Integer, XREObject> elementsXREIdToElement = receiver.getApplicationData().getElementsXREIdToElement();
            if (elementsXREIdToElement != null) {
                XREView view = (XREView) elementsXREIdToElement.get(Config.ROOTVIEW_ID);
                try {
                    painter.paint(view, canvas);
                } catch (XREPainterException e) {
                    Log.v(Config.APPLICATION_NAME, "Error occurs when painting.", e);
                }
            }
        }
    }
}